/**
 * Project Name:dynamicDomain
 * File Name:DynamicDomainService.java
 * Package Name:com.helper.domain.service
 * Date:2021年4月16日上午11:06:30
 * Copyright (c) 2021, hejiahua@szhuarong.com All Rights Reserved.
 *
*/

package com.helper.domain.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.helper.domain.config.DnsPodProperties;
import com.helper.domain.exception.CustomException;
import com.helper.domain.utils.IPUtil;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.dnspod.v20210323.DnspodClient;
import com.tencentcloudapi.dnspod.v20210323.models.DescribeRecordListRequest;
import com.tencentcloudapi.dnspod.v20210323.models.DescribeRecordListResponse;
import com.tencentcloudapi.dnspod.v20210323.models.ModifyRecordRequest;
import com.tencentcloudapi.dnspod.v20210323.models.ModifyRecordResponse;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * ClassName:DynamicDomainService <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2021年4月16日 上午11:06:30 <br/>
 * 
 * @author hejiahua
 * @version
 * @see
 */
@Service
@Slf4j
public class DynamicDomainService {
	public volatile static String cacheIP = "";
	@Autowired
	DnsPodProperties dnsPodProperties;

	/**
	 * 修改DNS解析记录
	 * 
	 * @Title: DNSRecordModify
	 * @throws CustomException
	 */
	public String DNSRecordModify(String queryIPType) throws CustomException {
		try {
			if(!StringUtils.isEmpty(cacheIP)) {
				log.info("IP无变动，当前IP：{}" , HttpUtil.get(String.format("http://%s:%s/pingip", cacheIP,dnsPodProperties.getPort())));
				return cacheIP ;
			}
		} catch (Exception e) {
			//
		}
		// 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
        // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性
        // 以下代码示例仅供参考，建议采用更安全的方式来使用密钥
        // 请参见：https://cloud.tencent.com/document/product/1278/85305
        // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
        Credential cred = new Credential(dnsPodProperties.getSecretId(), dnsPodProperties.getSecretKey());
        // 实例化一个http选项，可选的，没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("dnspod.tencentcloudapi.com");
        // 实例化一个client选项，可选的，没有特殊需求可以跳过
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品的client对象,clientProfile是可选的
        DnspodClient client = new DnspodClient(cred, "", clientProfile);
		
		
		try {
			if (StringUtils.isBlank(cacheIP)) {
				// 实例化一个请求对象,每个接口都会对应一个request对象
		        DescribeRecordListRequest req = new DescribeRecordListRequest();
		        req.setDomain(dnsPodProperties.getHostName());
		        req.setRecordType("A");
		        // 返回的resp是一个DescribeRecordListResponse的实例，与请求对象对应
		        DescribeRecordListResponse resp = client.DescribeRecordList(req);
		        // 输出json格式的字符串回包
		        log.info(AbstractModel.toJsonString(resp));
				cacheIP = resp.getRecordList()[0].getValue();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		String ip = null;
		try {
			HttpUtil.get(String.format("http://%s:%s/ping", cacheIP,dnsPodProperties.getPort()));
			ip = cacheIP;
		} catch (Exception e) {
			ip = IPUtil.getIP(queryIPType);
		}
		
		try {
			if (!cacheIP.equalsIgnoreCase(ip)) {
				log.info("IP变动，调用API修改记录值，当前IP：" + ip);
				ModifyRecordRequest reqmd = new ModifyRecordRequest();
		        reqmd.setRecordId(Long.valueOf(dnsPodProperties.getRecordId()));
		        reqmd.setDomain(dnsPodProperties.getHostName());
		        reqmd.setRecordType("A");
		        reqmd.setRecordLine("默认");
		        reqmd.setValue(ip);
		        // 返回的resp是一个ModifyRecordResponse的实例，与请求对象对应
		        ModifyRecordResponse respmd = client.ModifyRecord(reqmd);
		        // 输出json格式的字符串回包
		        log.info(AbstractModel.toJsonString(respmd));
				cacheIP = ip;
			} else {
				log.info("IP无变动，无需修改，当前IP:" + cacheIP);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cacheIP;
	}

}
